﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MX.Core.Http.WebAction
{
    public class BoundaryPostInfo : PostInfo
    {

        Dictionary<string, byte[]> fileList = new Dictionary<string, byte[]>();
        Dictionary<string, string> parameters = new Dictionary<string, string>();
        public string Boundary { get; private set; }
        public BoundaryPostInfo() :
            base(PostContentType.MultipartFormdata(Guid.NewGuid().ToString()), "utf-8")
        {
            Boundary = ContentType.Prefix;
        }

        public void AddFile(string fileName, byte[] data)
        {
            fileList.Add(fileName, data);
        }
        public void AddPars(string key, string value)
        {
            parameters.Add(key, value);
        }


        public override byte[] GetPostData()
        {
            var parsString = GetPostString();
            byte[] parsData = Encoding.GetEncoding(FormEncoding).GetBytes(parsString);
            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(parsData, 0, parsData.Length);
                foreach (var file in fileList)
                {
                    const string fileFormat = "\r\n--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
                    string fileHeader = string.Format(fileFormat, Boundary, file.Key, file.Key);
                    byte[] headerData = Encoding.UTF8.GetBytes(fileHeader);
                    ms.Write(headerData, 0, headerData.Length);
                    ms.Write(file.Value, 0, file.Value.Length);
                    byte[] footer = Encoding.UTF8.GetBytes(string.Format("\r\n--{0}--\r\n", Boundary));
                    ms.Write(footer, 0, footer.Length);
                }
                ms.Seek(0, SeekOrigin.Begin);
                byte[] postData = new byte[ms.Length];
                ms.Read(postData, 0, postData.Length);
                return postData;
            }
        }



        public override string GetPostString()
        {
            StringBuilder strForm = new StringBuilder();
            const string format = "\r\n--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}";
            foreach (string key in parameters.Keys)
            {
                strForm.AppendFormat(format, Boundary, key, parameters[key]);
            }
            return strForm.ToString();
        }
    }
}
